import { getUserInfoApi } from "@/apis/user";
import { defineStore } from "pinia";

export const userStore = defineStore("userStore", {
  state: () => {
    return {
      id: "",
      nickname: "",
      token: "",
      codeList: [],
    };
  },
  getters: {
    getUserId(state) {
      return state.id;
    },
    getToken(state) {
      return state.token;
    },
    getNickname(state) {
      return state.nickname;
    },
    getCodeList(state) {
      return state.codeList;
    },
  },
  actions: {
    setId(id: string) {
      this.id = id;
    },
    setNickname(nickname: string) {
      this.nickname = nickname;
    },
    setToken(token: string) {
      this.token = token;
    },
    getInfo() {
      return new Promise((resolve, reject) => {
        getUserInfoApi(this.id)
          .then((res) => {
            if (res && res.code == 200) {
              this.codeList = res.data.permissions;
              resolve(this.codeList);
            }
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
  },
  persist: [
    {
      pick: ["id", "nickname", "token"],
      storage: localStorage,
    },
  ],
});
